#! /usr/bin/env python
# -*- coding: utf-8 -*-

# *************************************************************
#     Filename @  manager.py
#       Author @  Huoty
#  Create date @  2015-12-15 14:53:23
#  Description @
# *************************************************************

from flask.ext.script import Manager, Server, prompt_bool
from kwsite import app, db
import MySQLdb
from os import getcwd

manager = Manager(app)
manager.add_command("runserver", Server('0.0.0.0', port=8181))

from kwsite.admin.models import initall, import_urls, import_essays

@manager.command
def initdb():
    """initialeze database"""

    try:
        conn = MySQLdb.connect(db="kwsite-flask", user="root", passwd="123456", host="127.0.0.1")
    except Exception, e:
        print "\n===================================================="
        print str(e).strip()
        print "====================================================\n"
        return None

    cur = conn.cursor()

    try:
        cur.execute("drop table if exists favorites")
        cur.execute("drop table if exists essay")
        cur.execute("drop table if exists album")
        cur.execute("drop table if exists administrator")
        cur.execute("drop table if exists record")
    except Exception, e:
        print "\n===================================================="
        print str(e).strip()
        print "====================================================\n"
        return None

    conn.commit()
    cur.close()
    conn.close()

    # initialeze all tables
    initall()

@manager.command
def dropall():
    """Drops all database tables"""

    if prompt_bool("Are you sure ? You will lose all your data !"):
        db.drop_all()

@manager.command
def importurls():
    import_urls(getcwd() + "/data/urls.json")

@manager.command
def importessays():
    import_essays(getcwd() + "/data/essays.json")



# Script starts from here

if __name__ == "__main__":
    manager.run()
